<?php

$thisPage = "saverequest";
$subpage = getRequestParameter("subpage", false);

TemplateHelper::useLayout("form");

$params = unserialize(stripslashes(getrequestparameter("params")));

addDataservice("save");

function buildLayout(&$smarty) {
    global $subpage;

    if ($subpage === false) {
        $smarty->assign("form", getSaveRequestFormData($smarty));
    } else if ($subpage == "success") {
    }
}

function executeService($serviceName, $params) {
    switch ($serviceName) {
        case "save" : { return service_save($params); }
    }
}

function service_save($params) {
    Database::loadModel("requests");
    $today = date("Y-m-d");
    Database::addNew(array(
        requestname => $params['name'],
        user_id => Auth::getUserProperty("user_id"),
        type => $params['type'],
        unit => $params['unit'],
        quantity => $params['quantity'],
        request_date => $today,
    ));
    return serviceSuccessfulWithRedirect(array(), "login", "success", array(
        redirecturl => "index.php"
    ));
}

function getPageHeader() {
    return TemplateHelper::getDefaultPageHeader();
}

function getPageFooter() {
    return TemplateHelper::getDefaultPageFooter();
}

function getSaveRequestFormData(&$smarty) {
    global $params;
    global $thisPage;

    Log::debug("Executing function: getSaveRequestFormData");
    if (Auth::isLoggedIn()) {
        $smarty->assign("request", array(
            name => $params['request'],
            type => $params['type'],
        ));
        return array(
            title => "Save request to immediate store",
            content => $smarty->fetch(TemplateHelper::getTemplateFile($thisPage, "saverequest_content"))
        );
    } else {
        return TemplateHelper::redirectPage("login", "", array(
            redirecturl => "index.php?choice=" . $thisPage . "&params=" . urlencode(serialize(array(
                request => $params['request'],
                type => $params['type'],
            )))
        ));
    }
}

?>
